package org.uned.agonzalo16.bitacora.web.tag;

import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.uned.agonzalo16.bitacora.dao.BlogContributionDao;
import org.uned.agonzalo16.bitacora.dao.UserDao;
import org.uned.agonzalo16.bitacora.domain.Blog;
import org.uned.agonzalo16.bitacora.domain.BlogContribution;
import org.uned.agonzalo16.bitacora.domain.User;
import org.uned.agonzalo16.bitacora.service.security.AuthenticatedUser;
import org.uned.agonzalo16.bitacora.service.security.AuthenticationProvider;

@Configurable
@SuppressWarnings("serial")
public class IsContributorTag extends TagSupport {

	private transient Blog blog;

	@Autowired
	private transient AuthenticationProvider authenticationProvider;

	@Autowired
	private transient UserDao userDao;

	@Autowired
	private transient BlogContributionDao blogContributionDao;

	public void setBlog(Blog blog) {
		this.blog = blog;
	}

	@Override
	public int doStartTag() throws JspException {

		AuthenticatedUser principal = authenticationProvider.getCurrentUserDetails();
		if (principal == null) {
			return SKIP_BODY;
		}

		User user = userDao.get(principal.getId());

		List<BlogContribution> blogs = blogContributionDao.findByUser(user);
		for (BlogContribution bc : blogs) {
			if (bc.getBlog().equals(blog)) {
				return EVAL_BODY_INCLUDE;
			}
		}
		return SKIP_BODY;
	}

}
